<?php

namespace App\Api;


use App\Http\Controllers\Controller;
use App\Http\Resources\CarResource;
use App\Models\Article;
use App\Models\Car;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CarController extends Controller
{
    public function index(Article $article)
    {
        $cars = CarResource::collection($article->cars);
        return $cars;
    }


    public function store(Request $request, Article $article, Car $car)
    {
        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $car = $article->cars()->create($request->input());
        $car->extra = ['price' => $request->price, 'time' => $request->time];
        $car->save();
        return $this->message('发表成功', $car->toArray());
    }

    public function show(Article $article, Car $car)
    {
        return new CarResource($car);
    }


    public function update(Request $request, Article $article, Car $car)
    {
        $request->validate([
            'title' => ['required', 'min:3'],
            'content' => ['required', 'min:5'],
            'preview' => ['required']
        ], [
            'preview.required' => '缩略图需上传'
        ]);
        $car->update($request->input());
        $car->extra = ['price' => $request->price, 'time' => $request->time];

        $car->save();
        return $this->message('修改成功', $car->toArray());
    }


    public function destroy(Article $article, Car $car)
    {
        $car->delete();
        return $this->message('删除成功');
    }

    public function carList()
    {
        return Car::where('recommend', 1)->orderBy('id', 'desc')->take(8)->get();
    }
}
